#include "sapackge.h"
#include <fstream>
#include <io.h>

#include "sastrucdef.h"

#define SAPATCH_DIR             "/patch"                        // 分离所在目录
#define ADRNBIN_NAME            "/adrn.bin"                     // adrnbin名称
#define REALBIN_NAME            "/real.bin"                     // realbin名称
#define SPRADRNBIN_NAME         "/spradrn.bin"                  // spradrnbin名称
#define SPRBIN_NAME             "/spr.bin"                      // sprbin名称

#define SPR_START               100000


using namespace std;

SaPackge::SaPackge() : EjLoadPackge()
{

}

bool SaPackge::open(std::string &path)
{
    if (access(path.c_str(), 0) != 0) return false;

    this->m_path = path;            //资源所在的目录

    if (!this->initRealBin()) return false;

    if (!this->initSprBin()) return false;

    return true;
}

void SaPackge::close(){

}

bool SaPackge::initRealBin()
{
    string adrnbinName = m_path + ADRNBIN_NAME;
    string realbinName = m_path + REALBIN_NAME;

    fstream af(adrnbinName, ios::in | ios::binary);

    if (!af.is_open()) return false;

    fstream rf(realbinName, ios::in | ios::binary);

    if (!rf.is_open()) {
        af.close();
        return false;
    }

    ADRNBIN adrn;

    af.read(reinterpret_cast<char *>(&adrn), sizeof(ADRNBIN));

    while (af.good())
    {
        m_adrn.insert(std::make_pair(adrn.bitmapno, adrn));

        af.read(reinterpret_cast<char *>(&adrn), sizeof(ADRNBIN));
    }


    return true;
}

bool SaPackge::initSprBin()
{
    string sprAdrnName = m_path + SPRADRNBIN_NAME;
    string sprBinName = m_path + SPRBIN_NAME;

    fstream af(sprAdrnName, ios::in | ios::binary);

    if (!af.is_open()) return false;

    fstream bf(sprBinName, ios::in | ios::binary);

    if (!bf.is_open()) {
        af.close();
        return false;
    }

    SPRADRN     sprAdrn;
    FRAMELIST   frameList;
    ANIMLIST    animList;
    SPRITEDATA  sprData;

    int         aniNum = 0;

    while (af.good() && bf.good()) {
        bf.read(reinterpret_cast<char *>(&sprAdrn), sizeof(sprAdrn));

        aniNum = sprAdrn.sprNo - SPR_START;

        af.seekg(sprAdrn.offset, ios::beg);

        for (int i = 0; i < sprAdrn.animSize; i++) {
            af.read(reinterpret_cast<char *>(&animList.info), sizeof(animList.info));

            if (animList.info.frameCnt <= 0) continue;

            for (ULONG j = 0; j < animList.info.frameCnt; j++) {
                af.read(reinterpret_cast<char *>(&frameList), sizeof(frameList));

                animList.frameList.push_back(frameList);
            }
            sprData.animlist.push_back(animList);
        }

        this->m_anim.insert(std::make_pair(aniNum, sprData));
    }

    return true;
}
